package com.dz.lm.web.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.constant.LmConstant;
import com.dz.lm.common.dto.AgentProductDTO;
import com.dz.lm.common.dto.ProductDTO;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.FileUploadUtil;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.service.moneyBar.MoneyBarService;
import com.dz.lm.service.pay.WxPayService;
import com.dz.lm.service.product.AgentProductService;
import com.dz.lm.service.product.ProductService;
import com.dz.lm.service.reminder.ReminderService;
import com.dz.lm.service.business.ApplyProductService;
import com.dz.lm.service.comment.CommentService;
import com.dz.lm.service.favorite.FavoriteService;
import com.dz.lm.service.goldagent.GoldAgentService;
import com.dz.lm.web.controller.BasicControl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

@RestController
@RequestMapping(value = "/rewriteUrl/product", produces = "application/json")
public class ProductController extends BasicControl {

	public Logger logger = LogManager.getLogger(ProductController.class);
	
    @Autowired
    private ProductService productService;
    
    @Autowired
    private AgentProductService agentProductService;
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private FavoriteService  favoriteService;
    
    @Autowired
    private ApplyProductService applyProductService;
    
	@Autowired
    private WxPayService wxPayService;
	
	@Autowired
    private MoneyBarService moneyBarService;    

    @Autowired
    private ReminderService reminderService;
    
    @Autowired
    private GoldAgentService goldAgentService;
    
    /**
     * 查询地理位置信息列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryLocalList")
    public Map<String, Object> qryLocalList(HttpServletRequest request) throws ServiceException {
		List<Map<String, Object>> localLsit = productService.qryLocalList();
		JSONObject subjo = new JSONObject();
		subjo.put("localList", localLsit);
    	subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
		return parameterEncrypt(request, subjo);
    }

    /**
     * 初始化首页产品列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/homeProductList")
    public Map<String, Object> homeProductList(HttpServletRequest request) throws ServiceException {
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		inparam.add("searchType");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}

		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		String position = param.get("position") != null? param.get("position").toString() : "";
		String size = param.get("size") != null? param.get("size").toString() : "";
		//province	省市编码
		String province = param.get("province") != null? param.get("province").toString() : "110100";
		//city	城市编码
		String city = param.get("city") != null? param.get("city").toString() : "";			
		//searchKey	搜索条件
		String searchKey = param.get("searchKey") != null? param.get("searchKey").toString() : "";
		//searchType搜索类型（01：推荐的需求、产品列表；02：附近的需求、产品列表；
		String searchType = param.get("searchType") != null? param.get("searchType").toString() : "";
		//infoType	数据类型	 非必填项目，说明如下：为空时，全部；01：需求信息；02：产品信息
		String infoType = param.get("infoType") != null? param.get("infoType").toString() : "";
		Map<String, Object> qryParam = new HashMap<String, Object>();
		if ("".equals(position))
			position= "0";
		if ("".equals(size))
			size= "10";
		qryParam.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		qryParam.put("size", Integer.valueOf(size));
		if (!"100000".equals(province)) {//全国：100000
			qryParam.put("province", province);
			//全北京 天津 上海 重庆
			if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
				qryParam.put("city", city);
		}
		if (!"".equals(searchKey.trim())){
			StringBuffer sb = new StringBuffer();
			searchKey = searchKey.trim();
			String key[] = searchKey.split(" ");
			for (String k : key) {
				sb.append(k);
				sb.append("%");
			}
			if (key != null && key.length > 0) {
				qryParam.put("searchKey", sb.substring(0, sb.length() - 1));
			}
		}
		//01：推荐的需求、产品列表；02:附近的需求、产品列表；
		qryParam.put("searchType", searchType);
		if (!"".equals(infoType)) {
			qryParam.put("infoType", infoType);
		}
		Map<String, Object> retData = productService.homeProductList(qryParam);
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("productList", retData.get("productList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterEncrypt(request, subjo);
    }
    
    /**
     * 新增需求
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/addNeeds")
    public Map<String, Object> addNeeds(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "needs");
    	}
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("province");
		inparam.add("city");
		inparam.add("productType");
		inparam.add("productName");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}

		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		//province	省市编码
		String province = param.get("province") != null? param.get("province").toString() : "110100";
		//city	城市编码
		String city = param.get("city") != null? param.get("city").toString() : "";			
		//productType	需求类型
		String productType = param.get("productType") != null? param.get("productType").toString() : "";
		//productName 产品名称
		String productName = param.get("productName") != null? param.get("productName").toString() : "";
		//labelDescription	需求标签介绍
		String labelDescription = param.get("labelDescription") != null? param.get("labelDescription").toString() : "";
		//productDescription	需求详细描述	
		String productDescription = param.get("productDescription") != null? param.get("productDescription").toString() : "";
		//agentFlag	是否允许被代理 固定（1：不允许）
		String agentFlag = param.get("agentFlag") != null? param.get("agentFlag").toString() : "1";
		//highLightFlag	高亮标签 固定（0：未购买或未支付）
		String highLightFlag = param.get("highLightFlag") != null? param.get("highLightFlag").toString() : "0";
		//autoUpdateFlag	自动更新 固定（0：未购买或未支付）
		String autoUpdateFlag = param.get("autoUpdateFlag") != null? param.get("autoUpdateFlag").toString() : "0";
		//机构创建标识（0：发布创建，1：机构创建）
		String organizationFlag = param.get("organizationFlag") != null? param.get("organizationFlag").toString() : "0";
		
		Map<String, Object> qryParam = new HashMap<String, Object>();
		qryParam.put("createUserId", request.getAttribute("userId"));
		qryParam.put("userId", request.getAttribute("userId"));
		if (!"100000".equals(province)) {//全国：100000
			qryParam.put("province", province);
			//全北京 天津 上海 重庆
			if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
				qryParam.put("city", city);
		}
		//需求类型
		qryParam.put("productType", productType);
		//信息类型（1：需求；2：产品）
		qryParam.put("infoType", "1");
		//产品名称
		qryParam.put("productName", productName);
		if (!"".equals(labelDescription)) {
			qryParam.put("labelDescription", labelDescription);
		}
		if (!"".equals(productDescription)) {
			qryParam.put("productDescription", productDescription);
		}
		qryParam.put("agentFlag", agentFlag);
		Date day = new Date();
		day = DateUtil.getDateAfter3Mon(day, 3);
    	long threeMon = day.getTime();
		qryParam.put("highLightFlag", highLightFlag);
		double amount = 0d;
		String body = "";
		//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
		String busPayType = "";
		if ("1".equals(highLightFlag)) {
			Timestamp highLightTime = new Timestamp(threeMon);
			qryParam.put("highLightTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_HIGILIGHT;
			busPayType = "1";
		}
		qryParam.put("autoUpdateFlag", autoUpdateFlag);
		if ("1".equals(autoUpdateFlag)) {
			Timestamp autoUpdateTime = new Timestamp(threeMon);
			qryParam.put("autoUpdateTime", autoUpdateTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
			busPayType = "2";
		}
		qryParam.put("organizationFlag", organizationFlag);
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			qryParam.put(key, imgUrl + urlMap.get(key).toString());
		}
		qryParam.put("highLightFlag", "0");
		qryParam.put("autoUpdateFlag", "0");
		productService.addNeeds(qryParam);
		Map<String, Object> retData = null;
		if (amount > 0.00) {
			qryParam.put("amount", amount);
			if ("1".equals(highLightFlag) && "1".equals(autoUpdateFlag)) {
				body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
				busPayType = "3";
			}
			qryParam.put("body", body);
			qryParam.put("device_info", param.get("deviceId"));
			qryParam.put("spbill_create_ip", param.get("ip"));
			qryParam.put("busPayType", busPayType);
			qryParam.put("productClass", "0");
			qryParam.put("payResult", "UNPAID");//未支付
			retData = wxPayService.unifiedOrder(qryParam);
		}
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "需求发布成功");
    	subjo.put("orderInfo", retData);
		return parameterEncrypt(request, subjo);
    }
    
    /**
     * 新增产品
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/addProduct")
    public Map<String, Object> addProduct(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "product");
    	}
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
    	JSONObject subjo = new JSONObject();;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		if (param.get("barId") == null || "".equals(param.get("barId"))) {
			inparam.add("province");
			inparam.add("city");
		}
		inparam.add("productType");
		inparam.add("productName");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		//province	省市编码
		String province = param.get("province") != null? param.get("province").toString() : "110100";
		//city	城市编码
		String city = param.get("city") != null? param.get("city").toString() : "";			
		//productType	需求类型
		String productType = param.get("productType") != null? param.get("productType").toString() : "";
		//productName 产品名称
		String productName = param.get("productName") != null? param.get("productName").toString() : "";
		//labelDescription	需求标签介绍
		String labelDescription = param.get("labelDescription") != null? param.get("labelDescription").toString() : "";
		//productDescription	需求详细描述	
		String productDescription = param.get("productDescription") != null? param.get("productDescription").toString() : "";
		//agentFlag	是否允许被代理 固定（1：不允许）
		String agentFlag = param.get("agentFlag") != null? param.get("agentFlag").toString() : "1";
		//highLightFlag	高亮标签 固定（0：未购买或未支付）
		String highLightFlag = param.get("highLightFlag") != null? param.get("highLightFlag").toString() : "0";
		//autoUpdateFlag	自动更新 固定（0：未购买或未支付）
		String autoUpdateFlag = param.get("autoUpdateFlag") != null? param.get("autoUpdateFlag").toString() : "0";
		//机构创建标识（0：发布创建，1：机构创建）
		String organizationFlag = param.get("organizationFlag") != null? param.get("organizationFlag").toString() : "0";
		Map<String, Object> qryParam = new HashMap<String, Object>();
		//辐射城市编码
		qryParam.put("radiatCityCode", param.get("radiatCityCode"));
		//辐射城市名称
		qryParam.put("radiatCityName", param.get("radiatCityName"));
		qryParam.put("createUserId", request.getAttribute("userId"));
		qryParam.put("userId", request.getAttribute("userId"));
		qryParam.put("label1", param.get("label1"));
		qryParam.put("label2", param.get("label2"));
		qryParam.put("label3", param.get("label3"));
		qryParam.put("label4", param.get("label4"));
		qryParam.put("applyRequire", param.get("applyRequire"));
		qryParam.put("provideMaterial", param.get("provideMaterial"));
		qryParam.put("payType", param.get("payType"));
		qryParam.put("payAmount", param.get("payAmount"));
		qryParam.put("payRate", param.get("payRate"));
		if (!"100000".equals(province)) {//全国：100000
			qryParam.put("province", province);
			//全北京 天津 上海 重庆
			if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
				qryParam.put("city", city);
		}
		//需求类型
		qryParam.put("productType", productType);
		//信息类型（1：需求；2：产品）
		qryParam.put("infoType", "2");
		//产品名称
		qryParam.put("productName", productName);
		if (!"".equals(labelDescription)) {
			qryParam.put("labelDescription", labelDescription);
		}
		if (!"".equals(productDescription)) {
			qryParam.put("productDescription", productDescription);
		}
		qryParam.put("agentFlag", agentFlag);
		Date day = new Date();
		day = DateUtil.getDateAfter3Mon(day, 3);
    	long threeMon = day.getTime();
		qryParam.put("highLightFlag", highLightFlag);
		double amount = 0d;
		String body = "";
		//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
		String busPayType = "";
		if ("1".equals(highLightFlag)) {
			Timestamp highLightTime = new Timestamp(threeMon);
			qryParam.put("highLightTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_HIGILIGHT;
			busPayType = "1";
		}
		qryParam.put("autoUpdateFlag", autoUpdateFlag);
		if ("1".equals(autoUpdateFlag)) {
			Timestamp autoUpdateTime = new Timestamp(threeMon);
			param.put("autoUpdateTime", autoUpdateTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
			busPayType = "2";
		}
		qryParam.put("organizationFlag", organizationFlag);
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			qryParam.put(key, imgUrl + urlMap.get(key).toString());
		}
		qryParam.put("barId", param.get("barId"));
		if (param.get("barId") != null && !"".equals(param.get("barId"))) {
			Map<String, Object> moneyBar = moneyBarService.getMoneyBarStateById(qryParam);
			if (moneyBar == null || moneyBar.isEmpty()) {
				subjo.put("result", "02");
		    	subjo.put("message", "钱吧数据不存在，产品发布失败");
				return parameterEncrypt(request, subjo);
			} else if (!"0".equals(moneyBar.get("validFlag"))){
				subjo.put("result", "03");
		    	subjo.put("message", "钱吧已下架，产品发布失败");
				return parameterEncrypt(request, subjo);
			} else if (!"2".equals(moneyBar.get("state"))){
				subjo.put("result", "04");
		    	subjo.put("message", "钱吧未审核通过，产品发布失败");
				return parameterEncrypt(request, subjo);
			}
		}
		qryParam.put("highLightFlag", "0");
		qryParam.put("autoUpdateFlag", "0");
		productService.addProduct(qryParam);
		Map<String, Object> retData = null;
		if (amount > 0.00) {
			qryParam.put("amount", amount);
			if ("1".equals(highLightFlag) && "1".equals(autoUpdateFlag)) {
				body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
				busPayType = "3";
			}
			qryParam.put("body", body);
			qryParam.put("device_info", param.get("deviceId"));
			qryParam.put("spbill_create_ip", param.get("ip"));
			qryParam.put("busPayType", busPayType);
			qryParam.put("productClass", "0");
			qryParam.put("payResult", "UNPAID");//未支付
			retData = wxPayService.unifiedOrder(qryParam);
			if ("01".equals(retData.get("result"))) {
				subjo.put("result", retData.get("result"));
		    	subjo.put("message", retData.get("message"));
		    	subjo.put("orderInfo", null);
			} else {
				subjo.put("result", "00");
		    	subjo.put("message", "产品发布成功");
		    	subjo.put("orderInfo", retData);
			}
		} else {
			subjo.put("result", "00");
	    	subjo.put("message", "产品发布成功");
	    	subjo.put("orderInfo", retData);
		}
		return parameterEncrypt(request, subjo);
    }

    /**
     * 修改需求信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/modifyNeeds")
    public Map<String, Object> modifyNeeds(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "needs");
    	}
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		inparam.add("province");
		inparam.add("city");
		inparam.add("productType");
		inparam.add("productName");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			param.put(key, imgUrl + urlMap.get(key).toString());
		}
		Date day = new Date();
		day = DateUtil.getDateAfter3Mon(day, 3);
    	long threeMon = day.getTime();
    	String highLightFlag = param.get("highLightFlag") != null ? param.get("highLightFlag").toString() : "";
    	String autoUpdateFlag = param.get("autoUpdateFlag") != null ? param.get("autoUpdateFlag").toString() : "";
    	Map<String, Object> product = productService.qryProductInfoByProductId(param);
    	String highLightFlagDB = product.get("highLightFlag") != null ? product.get("highLightFlag").toString() : "";
    	String autoUpdateFlagDB = product.get("autoUpdateFlag") != null ? product.get("autoUpdateFlag").toString() : "";
		double amount = 0d;
		String body = "";
		//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
		String busPayType = "";
		if (!"1".equals(highLightFlagDB) && "1".equals(highLightFlag)) {
			Timestamp highLightTime = new Timestamp(threeMon);
			param.put("highLightTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_HIGILIGHT;
			busPayType = "1";
			param.put("highLightFlag", "0");
		}
		if (!"1".equals(autoUpdateFlagDB) && "1".equals(autoUpdateFlag)) {
			Timestamp autoUpdateTime = new Timestamp(threeMon);
			param.put("autoUpdateTime", autoUpdateTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
			busPayType = "2";
			param.put("autoUpdateFlag", "0");
		}
		checkImage("image",param, 3);
		int count = productService.modifyNeeds(param);
		boolean payFlag = false;
		if (count == 1) {
			//物理删除用户操作删除的图片
			deleteImages(param.get("deleteFiles"));
			Map<String, Object> retData = null;
			if (amount > 0.00) {
				param.put("amount", amount);
				if (!"1".equals(highLightFlagDB) && "1".equals(highLightFlag) && !"1".equals(autoUpdateFlagDB) && "1".equals(autoUpdateFlag)) {
					body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
					busPayType = "3";
				}
				param.put("body", body);
				param.put("device_info", param.get("deviceId"));
				param.put("spbill_create_ip", param.get("ip"));
				param.put("busPayType", busPayType);
				param.put("productClass", "0");
				param.put("payResult", "UNPAID");//未支付
				param.put("agentType", "01");//01：修改产品
				Map<String, Object> productOrderInfo = wxPayService.qryProductOrderInfoByProductId(param);
				if (productOrderInfo == null || productOrderInfo.isEmpty()) {
					retData = wxPayService.unifiedOrder(param);
				} else {
					Object timeAgo0 = productOrderInfo.get("timeAgo");
					Object payResult0 = productOrderInfo.get("payResult");
					if (!"SUCCESS".equals(payResult0) && Long.valueOf(timeAgo0.toString()) < 3) {//存在3分钟内未支付完成的订单
						payFlag = true;
					} else {
						retData = wxPayService.unifiedOrder(param);
					}
				}
			}
			if (payFlag) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "存在未支付完成的订单，请3分钟后再试");
			} else {
				subjo.put("result", "00");
		    	subjo.put("message", "需求修改成功");
		    	subjo.put("orderInfo", retData);
			}
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "需求修改失败");
		}
		return parameterEncrypt(request, subjo);
    }
    
    /**
     * 修改产品信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/modifyProduct")
    public Map<String, Object> modifyProduct(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "product");
    	}
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
    	JSONObject subjo = new JSONObject();;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		if (param.get("barId") == null || "".equals(param.get("barId"))) {
			inparam.add("province");
			inparam.add("city");
		}
		inparam.add("productType");
		inparam.add("productName");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			param.put(key, imgUrl + urlMap.get(key).toString());
		}
		Date day = new Date();
		day = DateUtil.getDateAfter3Mon(day, 3);
    	long threeMon = day.getTime();
    	String highLightFlag = param.get("highLightFlag") != null ? param.get("highLightFlag").toString() : "";
    	String autoUpdateFlag = param.get("autoUpdateFlag") != null ? param.get("autoUpdateFlag").toString() : "";
    	Map<String, Object> product = productService.qryProductInfoByProductId(param);
    	String highLightFlagDB = product.get("highLightFlag") != null ? product.get("highLightFlag").toString() : "";
    	String autoUpdateFlagDB = product.get("autoUpdateFlag") != null ? product.get("autoUpdateFlag").toString() : "";
		double amount = 0d;
		String body = "";
		//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
		String busPayType = "";
		if (!"1".equals(highLightFlagDB) && "1".equals(highLightFlag)) {
			Timestamp highLightTime = new Timestamp(threeMon);
			param.put("highLightTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_HIGILIGHT;
			busPayType = "1";
			param.put("highLightFlag", "0");
		}
		if (!"1".equals(autoUpdateFlagDB) && "1".equals(autoUpdateFlag)) {
			Timestamp autoUpdateTime = new Timestamp(threeMon);
			param.put("autoUpdateTime", autoUpdateTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
			busPayType = "2";
			param.put("autoUpdateFlag", "0");
		}
		checkImage("image",param, 3);
		int count = productService.modifyProduct(param);
		boolean payFlag = false;
		if (count == 1) {
			//物理删除用户操作删除的图片
			deleteImages(param.get("deleteFiles"));
			Map<String, Object> retData = null;
			if (amount > 0.00) {
				param.put("amount", amount);
				if (!"1".equals(highLightFlagDB) && !"1".equals(autoUpdateFlagDB) &&  "1".equals(highLightFlag) && "1".equals(autoUpdateFlag)) {
					body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
					busPayType = "3";
				}
				param.put("body", body);
				param.put("device_info", param.get("deviceId"));
				param.put("spbill_create_ip", param.get("ip"));
				param.put("busPayType", busPayType);
				param.put("productClass", "0");
				param.put("payResult", "UNPAID");//未支付
				param.put("agentType", "01");//01：修改产品
				Map<String, Object> productOrderInfo = wxPayService.qryProductOrderInfoByProductId(param);
				if (productOrderInfo == null || productOrderInfo.isEmpty()) {
					retData = wxPayService.unifiedOrder(param);
				} else {
					Object timeAgo0 = productOrderInfo.get("timeAgo");
					Object payResult0 = productOrderInfo.get("payResult");
					if (!"SUCCESS".equals(payResult0) && Long.valueOf(timeAgo0.toString()) < 3) {//存在3分钟内未支付完成的订单
						payFlag = true;
					} else {
						retData = wxPayService.unifiedOrder(param);
					}
				}
			}
			if (payFlag) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "存在未支付完成的订单，请3分钟后再试");
			} else {
				subjo.put("result", "00");
		    	subjo.put("message", "产品修改成功");
		    	subjo.put("orderInfo", retData);
			}
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "产品修改失败");
		}
		return parameterEncrypt(request, subjo);
    }
    
    @ResponseBody
    @RequestMapping("/getProductDetail")
	public Map<String, Object> getProductDetail(HttpServletRequest request) throws ServiceException {
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		JSONObject subjo = new JSONObject();
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
		ProductDTO productDTO = productService.selectByPrimaryKey(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
		subjo.put("productInfo", productDTO);
		return parameterEncrypt(request, subjo);
	}
    
    @ResponseBody
    @RequestMapping("/getAgentProductDetail")
	public Map<String, Object> getAgentProductDetail(HttpServletRequest request) throws ServiceException {
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		JSONObject subjo = new JSONObject();
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
		AgentProductDTO AgentProductDTO = agentProductService.selectByPrimaryKey(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
		subjo.put("productInfo", AgentProductDTO);
		return parameterEncrypt(request, subjo);
    }
    
    @ResponseBody
    @RequestMapping("/applyProduct")
    public Map<String, Object> applyProduct(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
    	param.put("userId", request.getAttribute("userId"));
    	Map<String, Object> returnMap = applyProductService.insert(param);
		JSONObject subjo = new JSONObject();
		subjo.put("result", returnMap.get("result"));
		subjo.put("message", returnMap.get("message"));
		return parameterEncrypt(request, subjo);
    }
    
    @ResponseBody
    @RequestMapping("/addProductFavorite")
	public Map<String, Object> addProductFavorite(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		/*
		 * String productId = "1"; String agentProductId = "1"; String userId = "1";
		 */
		Map<String, Object> retData = favoriteService.insert(param);
		JSONObject subjo = new JSONObject();
		subjo.put("result", retData.get("result"));
		subjo.put("message", retData.get("message"));
		return parameterEncrypt(request, subjo);
	}

    @ResponseBody
    @RequestMapping("/qryProductFavoriteList")
	public Map<String, Object> qryProductFavoriteList(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		JSONObject subjo = new JSONObject();
		// 参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
				subjo.put("result", "01");
				subjo.put("message", "参数" + in + "异常");
				return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		String position = param.get("position") != null ? param.get("position").toString() : "";
		String size = param.get("size") != null ? param.get("size").toString() : "";
		Map<String, Object> qryParam = new HashMap<String, Object>();
		if ("".equals(position))
			position = "0";
		if ("".equals(size))
			size = "10";
		qryParam.put("userId", request.getAttribute("userId"));
		qryParam.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		qryParam.put("size", Integer.valueOf(size));
//		Map<String, Object> qryParam = new HashMap<String, Object>();
//		qryParam.put("userId", 3);
//		qryParam.put("position", Integer.valueOf("0") * Integer.valueOf("10"));
//		qryParam.put("size", Integer.valueOf("10"));
//		JSONObject subjo = new JSONObject();
		Map<String, Object> retData = favoriteService.qryProductFavoriteList(qryParam);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("favoriteList", retData.get("favoriteList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf("10") > 0) {
			page = count / Integer.valueOf("10") + 1;
		} else {
			page = count / Integer.valueOf("10");
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterEncrypt(request, subjo);
	}
    
    @ResponseBody
    @RequestMapping("/qryProductCommentList")
	public Map<String, Object> qryProductCommentList(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		JSONObject subjo = new JSONObject();
		Map<String, Object> retData = commentService.qryProductCommentList(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("productCommentList", retData.get("productCommentList"));
    	subjo.put("agentProductCommentList", retData.get("agentProductCommentList"));
		return parameterEncrypt(request, subjo);
	}

    @ResponseBody
    @RequestMapping("/addProductComment")
	public Map<String, Object> addProductComment(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
		JSONObject _reqData = JSONObject.parseObject(reqData);
		JSONObject subjo = new JSONObject();
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		int i = commentService.insert(param);
		if (i == 1) {
			subjo.put("result", "00");
			subjo.put("message", "评论成功");
		} else {
			subjo.put("result", "-1");
			subjo.put("message", "评论失败");
		}
		return parameterEncrypt(request, subjo);
	}
    
    /**
     * 筛选页搜索
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/siftingSearch")
    public Map<String, Object> siftingSearch(HttpServletRequest request) throws ServiceException {
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}

		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		String position = param.get("position") != null? param.get("position").toString() : "";
		String size = param.get("size") != null? param.get("size").toString() : "";
		//province	省市编码
		String province = param.get("province") != null? param.get("province").toString() : "110100";
		//city	城市编码
		String city = param.get("city") != null? param.get("city").toString() : "";			
		//searchKey	搜索条件
		String searchKey = param.get("searchKey") != null? param.get("searchKey").toString() : "";
		//sortType	排序类型（0：默认综合排序，1：距离最近，2：时间最近）
		String sortType = param.get("sortType") != null? param.get("sortType").toString() : "";
		//productType	产品类型（01：凭信用，02：小抵押，03：车，04：房：05：极速贷，06：信用卡，07：POS专区，08：其他）
		String productType = param.get("productType") != null? param.get("productType").toString() : "";
		//infoType	数据类型	 非必填项目，说明如下：为空时，全部；01：需求信息；02：产品信息
		String infoType = param.get("infoType") != null? param.get("infoType").toString() : "";
		//authFlag	实名认证标识（空：全部 0：已实名1：未实名）
		String authFlag = param.get("authFlag") != null? param.get("authFlag").toString() : "";
		//orgAuthFlag	结构认证标识（空：全部  0：已进行机构认证 1：未进行机构认证）
		String orgAuthFlag = param.get("orgAuthFlag") != null? param.get("orgAuthFlag").toString() : "";
		//createAgentFlag	创建/代理标识（空：全部	0：创建的产品 1：代理的产品）
		String createAgentFlag = param.get("createAgentFlag") != null? param.get("createAgentFlag").toString() : "";
		//applyAgentFlag	是否允许申请代理标识（空：全部 0：允许被代理 1：不允许被代理）
		String applyAgentFlag = param.get("applyAgentFlag") != null? param.get("applyAgentFlag").toString() : "";
		Map<String, Object> qryParam = new HashMap<String, Object>();
		if ("".equals(position))
			position= "0";
		if ("".equals(size))
			size= "10";
		qryParam.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		qryParam.put("size", Integer.valueOf(size));
		if (!"100000".equals(province)) {//全国：100000
			qryParam.put("province", province);
			//全北京 天津 上海 重庆
			if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
				qryParam.put("city", city);
		}
		if (!"".equals(searchKey.trim())){
			StringBuffer sb = new StringBuffer();
			searchKey = searchKey.trim();
			String key[] = searchKey.split(" ");
			for (String k : key) {
				sb.append(k);
				sb.append("%");
			}
			if (key != null && key.length > 0) {
				qryParam.put("searchKey", sb.substring(0, sb.length() - 1));
			}
		}
		if (!"".equals(infoType)) {
			qryParam.put("infoType", infoType);
		}
		if (!"".equals(sortType)) {
			qryParam.put("sortType", sortType);
		}
		if (!"".equals(productType)) {
			qryParam.put("productType", productType);
		}
		if (!"".equals(authFlag)) {
			qryParam.put("authFlag", authFlag);
		}
		if (!"".equals(orgAuthFlag)) {
			qryParam.put("orgAuthFlag", orgAuthFlag);
		}
		if (!"".equals(createAgentFlag)) {
			qryParam.put("createAgentFlag", createAgentFlag);
		}
		if (!"".equals(applyAgentFlag)) {
			qryParam.put("applyAgentFlag", applyAgentFlag);
		}
		Map<String, Object> retData = productService.siftingSearch(qryParam);
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("productList", retData.get("productList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterEncrypt(request, subjo);
    }
    
    /**
     * 创建的产品的代理产品列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/agentProductList")
    public Map<String, Object> agentProductList(HttpServletRequest request) throws ServiceException {
		String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		inparam.add("productId");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";		
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		Map<String, Object> retData = productService.agentProductList(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("productList", retData.get("productList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterEncrypt(request, subjo);
    }
    
    @RequestMapping(value = "/home/hot")
    public Map<String, Object> listHomeHot(HttpServletRequest request) {
        JSONObject subjo = new JSONObject();
        List<ProductDTO> productDTOS = productService.listHotProducts();
        subjo.put("products", productDTOS);
        subjo.put("result", "00");
        subjo.put("message", "");
        return parameterEncrypt(request, subjo);
    }

    @RequestMapping(value = "/home/selected")
    public Map<String, Object> listHomeSelected(HttpServletRequest request) {
        JSONObject subjo = new JSONObject();
        subjo.put("products", productService.listSelectedProducts());
        subjo.put("result", "00");
        subjo.put("message", "");
        return parameterEncrypt(request, subjo);
    }
    
    /**
     * 可发布产品列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/releasableProducts")
    public Map<String, Object> releasableProducts(HttpServletRequest request) {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	Map<String, Object> reqParam = JsonUtils.readValue(_reqData.toString());
    	//产品ID
    	Object productId = reqParam.get("productId");
		try {
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	if (productId != null && !"".equals(productId.toString())) {
	    		param.put("productId", productId);
	    	}
			param.put("agentId", request.getAttribute("userId"));
			param.put("userId", request.getAttribute("userId"));
			List<Map<String, Object>> agentProducts;
			agentProducts = productService.releasableProducts(param);
			subjo.put("result", "00");  
	    	subjo.put("message", "查询成功");
	    	subjo.put("agentProducts", agentProducts);
			return parameterEncrypt(request, subjo);
		} catch (ServiceException e) {
			subjo.put("result", "01");  
	    	subjo.put("message", "数据处理异常");
			return parameterEncrypt(request, subjo);
		}
    }
    
    /**
     * 申请代理
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/applyProductAgent")
    public Map<String, Object> applyProductAgent(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		inparam.add("agentClass");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("agentId", request.getAttribute("userId"));
		param.put("userId", request.getAttribute("userId"));
		//发布标识（0：待发布，1：已发布）
		String releaseFlag = "0"; 
		//审核状态（0：待审核，1：审核通过）
		String state = "";
		//钱吧创建的产品ID
		String productId = param.get("productId") != null? param.get("productId").toString() : "";
		//agentClass(1：一级代理，2：二级代理)
		String agentClass = param.get("agentClass") != null? param.get("agentClass").toString() : "";
		//原始产品ID
		int originalProductId = 0;
		//代理的产品ID
		int agentProductId = 0;
		String type = "";
		if ("".equals(productId)) {
	    	subjo = new JSONObject();
			subjo.put("result", "01");
	    	subjo.put("message", "产品编码不能为空");
	    	return parameterEncrypt(request, subjo);
		} else if ("".equals(agentClass)) {
			subjo = new JSONObject();
			subjo.put("result", "01");
	    	subjo.put("message", "代理等级不能为空");
	    	return parameterEncrypt(request, subjo);
		} else if ("1".equals(agentClass)) {
			agentProductId = Integer.valueOf(productId);
			originalProductId = Integer.valueOf(productId);
			state = "0";
			type = "2";
		} else if ("2".equals(agentClass)) {
			agentProductId = (int) productService.qryByParentId(param).get("productId");
			originalProductId = (int) productService.qryByParentId(param).get("originalProductId");
			state = "0";
			type = "3";
		}
		param.put("agentProductId", agentProductId);
		param.put("originalProductId", originalProductId);
		param.put("releaseFlag", releaseFlag);
		param.put("state", state);
		Map<String, Object> userInfo = goldAgentService.qryMyPromoCode(param);
		if ("2".equals(agentClass) && "1".equals(userInfo.get("goldAgentFlag"))) {
			subjo.put("result", "06");
	    	subjo.put("message", "黄金代理人不可申请二级代理");
	    	return parameterEncrypt(request, subjo);
		}
		int count = agentProductService.qryProductCountByAgentId(param);
		if (count > 0) {
			subjo.put("result", "03");
	    	subjo.put("message", "钱吧创建者不允许代理钱吧下所有产品");
		} else {
			count = agentProductService.qryAgentProductCountByAgentId(param);
			if (count > 0) {
				if (count == 3) {
					subjo.put("result", "04");
			    	subjo.put("message", "您已取消该产品代理权，请于一个月后再次申请");
				} else {
					subjo.put("result", "05");
			    	subjo.put("message", "您已提交申请，请我的代理产品种查询结果");
				}
			} else {
				Map<String, Object> retData = productService.applyProductAgent(param);
				if ((int)retData.get("count") == 1) {
					subjo.put("result", "00");
					if ("0".equals(retData.get("state"))) {
						subjo.put("message", "申请成功，待审核");
				    	Map<String, Object> agentProduct = productService.qryAgentProduct(param);
				    	subjo.put("productId", agentProduct.get("productId"));
				    	Object createUserId = agentProduct.get("createUserId");
				    	Map<String, Object> insertParam = new HashMap<String, Object>();
				    	insertParam.put("userId", createUserId);
				    	insertParam.put("type", type);
				    	insertParam.put("operatedUserId", request.getAttribute("userId"));
				    	if ("2".equals(agentClass)) {
				    		insertParam.put("productId", agentProductId);
				    	}
				    	reminderService.addReminder(insertParam);
				    	insertParam.put("platform", param.get("platform"));
			            String pushTitle = "【微介】代理人认证审批提醒";
			            String pushContent = "您有新的代理人认证申请记录待受理，请注意查收";
			            insertParam.put("pushTitle", pushTitle);
			            insertParam.put("pushContent", pushContent);
				    	reminderService.sendMessagePush(insertParam);
					} else {
						subjo.put("message", "申请成功，请在发布代理产品模块下发布该产品");
					}
				} else {
					subjo.put("result", "01");
			    	subjo.put("message", "申请代理保存失败");
				}
			}
		}
    	return parameterEncrypt(request, subjo);
    }
    
    /**
     * 取消代理
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/cancelProductAgent")
    public Map<String, Object> cancelProductAgent(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("agentId", request.getAttribute("userId"));
		param.put("userId", request.getAttribute("userId"));
		//发布标识（0：待发布，1：已发布）
		String releaseFlag = "0"; 
		//代理产品ID
		String productId = param.get("productId") != null? param.get("productId").toString() : "";
		if ("".equals(productId)) {
	    	subjo = new JSONObject();
			subjo.put("result", "01");
	    	subjo.put("message", "产品编码不能为空");
	    	return parameterEncrypt(request, subjo);
		}
		param.put("releaseFlag", releaseFlag);
		Map<String, Object> retData = agentProductService.cancelProductAgentByAgentId(param);
		subjo.put("result", retData.get("result"));
    	subjo.put("message", retData.get("message"));
		return parameterEncrypt(request, subjo);
    }
	
    /**
     * 代理产品发布
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/addAgentProduct")
    public Map<String, Object> addAgentProduct(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		inparam.add("province");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
		String productId = param.get("productId") != null? param.get("productId").toString() : "";
		if ("".equals(productId)) {
			subjo.put("result", "01");
	    	subjo.put("message", "产品编码不能为空");
	    	return parameterEncrypt(request, subjo);
		}
		Map<String, Object> agentProductInfo = productService.qryByParentId(Integer.valueOf(productId));
		Object state = agentProductInfo.get("state");
		if (!"1".equals(state)) {
			subjo.put("result", "02");
	    	subjo.put("message", "代理申请处于审核中，代理产品发布失败");
		} else {
			//校验发布省市是否在辐射城市范围内
			//province	省市编码
			String province = param.get("province") != null? param.get("province").toString() : "";
			//city	城市编码
			String city = param.get("city") != null? param.get("city").toString() : "";
			if ("".equals(province)) {
				subjo.put("result", "01");
		    	subjo.put("message", "请选择发布城市");
		    	return parameterEncrypt(request, subjo);
			}
			String inCity = province;
			if (!"".equals(city)) {
				inCity = inCity + ":" + city;
			}
			boolean isExit = false;
			if (agentProductInfo.get("radiatCityCode") != null && !"".equals(agentProductInfo.get("radiatCityCode"))) {
				String radiatCity[] = agentProductInfo.get("radiatCityCode").toString().split(";");
				for (String rCity : radiatCity) {
					if (rCity.indexOf("110100") >= 0 
							|| rCity.indexOf("120100") >= 0 
							|| rCity.indexOf("310100") >= 0 
							|| rCity.indexOf("500100") >= 0) {
						rCity = rCity.substring(0, 6);
					}
					if (rCity != null && inCity.indexOf(rCity) >= 0) {
						isExit = true;
						break;
					}
				}
			}
			if (!isExit) {
				subjo.put("result", "01");
		    	subjo.put("message", "该发布城市不在产品的辐射范围内，请重新选择！");
		    	return parameterEncrypt(request, subjo);
			}
			//发布标识（0：待发布，1：已发布）
			String releaseFlag = "1"; 
			param.put("releaseFlag", releaseFlag);
			Date day = new Date();
			day = DateUtil.getDateAfter3Mon(day, 3);
	    	long threeMon = day.getTime();
			Timestamp highLightTime = new Timestamp(threeMon);
	    	String highLightFlag = param.get("highLightFlag") != null ? param.get("highLightFlag").toString() : "";
	    	String autoUpdateFlag = param.get("autoUpdateFlag") != null ? param.get("autoUpdateFlag").toString() : "";
			double amount = 0d;
			String body = "";
			//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
			String busPayType = "";
	    	if ("1".equals(highLightFlag)) {
				param.put("highLightTime", highLightTime);
				amount = amount + 10;
				body = LmConstant.LM_PAY_BODY_HIGILIGHT;
				busPayType = "1";
			}
			if ("1".equals(autoUpdateFlag)) {
				param.put("autoUpdateTime", highLightTime);
				amount = amount + 10;
				body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
				busPayType = "2";
			}
	    	param.put("highLightFlag", "0");
	    	param.put("autoUpdateFlag", "0");
			int count = productService.updateAgentProduct(param);
			Map<String, Object> retData = null;
			if (amount > 0.00) {
				param.put("amount", amount);
				if ("1".equals(highLightFlag) && "1".equals(autoUpdateFlag)) {
					body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
					busPayType = "3";
				}
				param.put("body", body);
				param.put("device_info", param.get("deviceId"));
				param.put("spbill_create_ip", param.get("ip"));
				param.put("busPayType", busPayType);
				param.put("productClass", "1");
				param.put("payResult", "UNPAID");//未支付
				param.put("agentType", "00");//代理类型
				retData = wxPayService.unifiedOrder(param);
			}
			if (count == 1) {
				subjo.put("result", "00");
		    	subjo.put("message", "代理产品发布成功");
		    	subjo.put("orderInfo", retData);
			} else {
				subjo.put("result", "01");
		    	subjo.put("message", "代理产品发布失败");
			}
		}
    	return parameterEncrypt(request, subjo);
    }
    
    /**
     * 修改代理产品
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/modifyAgentProduct")
    public Map<String, Object> modifyAgentProduct(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		inparam.add("province");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		param.put("userId", request.getAttribute("userId"));
		String productId = param.get("productId") != null? param.get("productId").toString() : "";
		if ("".equals(productId)) {
			subjo.put("result", "01");
	    	subjo.put("message", "产品编码不能为空");
	    	return parameterEncrypt(request, subjo);
		}
		Map<String, Object> agentProductInfo = productService.qryByParentId(Integer.valueOf(productId));
		//校验发布省市是否在辐射城市范围内
		//province	省市编码
		String province = param.get("province") != null? param.get("province").toString() : "";
		//city	城市编码
		String city = param.get("city") != null? param.get("city").toString() : "";
		if ("".equals(province)) {
			subjo.put("result", "01");
	    	subjo.put("message", "请选择发布城市");
	    	return parameterEncrypt(request, subjo);
		}
		String inCity = province;
		if (!"".equals(city)) {
			inCity = inCity + ":" + city;
		}
		boolean isExit = false;
		if (agentProductInfo.get("radiatCityCode") != null && !"".equals(agentProductInfo.get("radiatCityCode"))) {
			String radiatCity[] = agentProductInfo.get("radiatCityCode").toString().split(";");
			for (String rCity : radiatCity) {
				if (rCity.indexOf("110100") >= 0 
						|| rCity.indexOf("120100") >= 0 
						|| rCity.indexOf("310100") >= 0 
						|| rCity.indexOf("500100") >= 0) {
					rCity = rCity.substring(0, 6);
				}
				if (rCity != null && inCity.indexOf(rCity) >= 0) {
					isExit = true;
					break;
				}
			}
		}
		if (!isExit) {
			subjo.put("result", "01");
	    	subjo.put("message", "该发布城市不在产品的辐射范围内，请重新选择！");
	    	return parameterEncrypt(request, subjo);
		}
		Object releaseFlag = agentProductInfo.get("releaseFlag");
		if ("1".equals(releaseFlag)) {
			param.remove("releaseFlag");
		} else {
			param.put("releaseFlag", releaseFlag);
		}
		Date day = new Date();
		day = DateUtil.getDateAfter3Mon(day, 3);
    	long threeMon = day.getTime();
		Timestamp highLightTime = new Timestamp(threeMon);
    	String highLightFlag = param.get("highLightFlag") != null ? param.get("highLightFlag").toString() : "";
    	String autoUpdateFlag = param.get("autoUpdateFlag") != null ? param.get("autoUpdateFlag").toString() : "";
    	Map<String, Object> product = agentProductService.qryAgentProductInfoByProductId(param);
    	String highLightFlagDB = product.get("highLightFlag") != null ? product.get("highLightFlag").toString() : "";
    	String autoUpdateFlagDB = product.get("autoUpdateFlag") != null ? product.get("autoUpdateFlag").toString() : "";
		double amount = 0d;
		String body = "";
		//支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新）
		String busPayType = "";
		if (!"1".equals(highLightFlagDB) && "1".equals(highLightFlag)) {
			param.put("highLightTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_HIGILIGHT;
			busPayType = "1";
			param.put("highLightFlag", "0");
		}
		if (!"1".equals(autoUpdateFlagDB) &&  "1".equals(autoUpdateFlag)) {
			param.put("autoUpdateTime", highLightTime);
			amount = amount + 10;
			body = LmConstant.LM_PAY_BODY_AUTO_FRESH;
			busPayType = "2";
			param.put("autoUpdateFlag", "0");
		}
		int count = productService.updateAgentProduct(param);
		boolean payFlag = false;
		if (count == 1) {
			Map<String, Object> retData = null;
			if (amount > 0.00) {
				param.put("amount", amount);
				if (!"1".equals(highLightFlagDB) && !"1".equals(autoUpdateFlagDB) &&  "1".equals(highLightFlag) && "1".equals(autoUpdateFlag)) {
					body = LmConstant.LM_PAY_BODY_HIGH_AUTO_FRESH;
					busPayType = "3";
				}
				param.put("body", body);
				param.put("device_info", param.get("deviceId"));
				param.put("spbill_create_ip", param.get("ip"));
				param.put("busPayType", busPayType);
				param.put("productClass", "1");
				param.put("payResult", "UNPAID");//未支付
				param.put("agentType", "00");//代理类型
				Map<String, Object> productOrderInfo = wxPayService.qryProductOrderInfoByProductId(param);
				if (productOrderInfo == null || productOrderInfo.isEmpty()) {
					retData = wxPayService.unifiedOrder(param);
				} else {
					Object timeAgo0 = productOrderInfo.get("timeAgo");
					Object payResult0 = productOrderInfo.get("payResult");
					if (!"SUCCESS".equals(payResult0) && Long.valueOf(timeAgo0.toString()) < 3) {//存在3分钟内未支付完成的订单
						payFlag = true;
					} else {
						retData = wxPayService.unifiedOrder(param);
					}
				}
			}
			if (payFlag) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "存在未支付完成的订单，请3分钟后再试");
			} else {
				subjo.put("result", "00");
		    	subjo.put("message", "代理产品修改成功");
		    	subjo.put("orderInfo", retData);
			}
		} else {
			subjo.put("result", "01");
	    	subjo.put("message", "代理产品修改失败");
		}
    	return parameterEncrypt(request, subjo);
    }
    
    /**
     * 刷新产品更新时间
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/refreshProduct")
    public Map<String, Object> refreshProduct(HttpServletRequest request) throws ServiceException {
    	String reqData = request.getAttribute("reqData") != null ? request.getAttribute("reqData").toString() : "";
    	JSONObject _reqData = JSONObject.parseObject(reqData);
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("productId");
		inparam.add("agentType");
		for (String in : inparam) {
			if (!_reqData.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterEncrypt(request, subjo);
			}
		}
		Map<String, Object> param = JsonUtils.readValue(_reqData.toString());
		String productId = param.get("productId") != null? param.get("productId").toString() : "";
		String agentType = param.get("agentType") != null? param.get("agentType").toString() : "";
		if ("".equals(productId)) {
			subjo.put("result", "02");
	    	subjo.put("message", "产品编码不能为空");
	    	return parameterEncrypt(request, subjo);
		} else if("".equals(agentType)) {
			subjo.put("result", "02");
	    	subjo.put("message", "产品类别不能为空");
	    	return parameterEncrypt(request, subjo);
		}
		Map<String, Object> qryParam = new HashMap<String, Object>();
		qryParam.put("productId", productId);
		int count = 0;
		if ("1".equals(agentType)) {
			count = productService.modifyProduct(qryParam);
		} else if ("2".equals(agentType)) {
			count = productService.updateAgentProduct(qryParam);
		}
		if (count == 1) {
			subjo.put("result", "00");
	    	subjo.put("message", "刷新成功");
		} else {
			subjo.put("result", "01");
	    	subjo.put("message", "刷新失败");
		}
    	return parameterEncrypt(request, subjo);
    }
}
